// 默认路由
import home from "./components/home.js";
import welcome from "./views/welcome.js";
import login from "./views/login.js";
// 动态路由
import Users from "./views/users.js";
import Roles from "./views/roles.js";
import GoodsCate from "./views/categories.js";
import GoodsList from "./components/goods.js";

const Rule = {
  users: { path: "/users", component: Users },
  roles: { path: "/roles", component: Roles },
  goods: { path: "/goods", component: GoodsList },
  categories: { path: "/categories", component: GoodsCate },
};
const router = new VueRouter({
  mode: "hash",
  routes: [
    {
      path: "/",
      component: home,
      redirect: "/welcome",
      children: [{ path: "/welcome", component: welcome }],
    },
    {
      path: "/login",
      component: login,
      loading: {
        template: `<h3>加载中...</h3>`,
      },
      error: {
        template: `<h3>加载失败了,请重新加载</h3>`,
      },
      delay: 200,
      timeout: 3000,
    },
    {
      path: "*",
      component: {
        template: "<h3>您访问的地址丢失了哦</h3>",
      },
    },
  ],
});
router.beforeEach((to, from, next) => {
  if (to.path === "/login") {
    next();
  } else {
    const token = sessionStorage.getItem("jauthToken");
    if (!token) {
      next("/login");
    } else {
      next();
    }
  }
});
import store from './store.js'
const ruleMapping = {
  'users': Rule.users,
  'roles': Rule.roles,
  'goods': Rule.goods,
  'categories': Rule.categories
}
export function initDynamicRoutes() {
  const currentRoutes = router.options.routes
  const rightList = store.state.rightList
  rightList.forEach((one) => {
    one.children.forEach(two => {
      const temp = ruleMapping[two.path]
      temp.meta = two.rights
      currentRoutes[0].children.push(temp)
    })
  })
  console.log("currentRoutes", currentRoutes);
  router.addRoutes(currentRoutes)
}
export default router